import React from 'react'
import { Icon } from 'antd'
import { WeaSelect } from "ecCom";
import Panel from './Panel';
import {observer} from 'mobx-react';
import {toJS} from 'mobx';
import { WeaPopoverHrm,WeaLocaleProvider } from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;
@observer
export default class Cell extends React.Component {

  componentDidMount() {
    this.adjustWrapHeight();
    this.adjustWrapWidth();
    if((window.location.href.indexOf('isFromMobile') > -1) && window.parent && window.parent.cancelLodingMask) {
      window.parent.cancelLodingMask('none');
    }
  }
  componentDidUpdate() {
    this.adjustWrapWidth();
    this.adjustWrapHeight();
  }

  //移动端调整外层包裹元素的高度，防止出现背景空白的情况
  adjustWrapHeight() {
    const { islastArr, wrapBoxCount} = this.props;
    if(window.location.href.indexOf('isFromMobile') > -1 && islastArr) {
      let wrapBoxHeight = (wrapBoxCount - 1) * 147 + 72;
      let container = document.getElementById('container');
      let containerHeight = container.offsetHeight;
      let wrapBox = document.getElementById('smartGuessPicBox');
      let parentDiv = wrapBox.parentNode.parentNode;
      parentDiv.onscroll = function() {
        let obj = document.getElementById('wfFrontOperator-container');
        if(obj) {
          obj.style.visibility = 'hidden'
        }
      }
      if(containerHeight > wrapBoxHeight) {
        parentDiv.setAttribute('class', 'smart-wrap-div');
        parentDiv.style.overflowY = 'auto';
        parentDiv.style.backgroundColor = '#f4f4f4';
        wrapBox.style.height = containerHeight + 10 + 'px';
      } else {
        parentDiv.setAttribute('class', 'smart-wrap-div');
        parentDiv.style.overflowY = 'auto';
        parentDiv.style.backgroundColor = '#f4f4f4';
        wrapBox.style.height = wrapBoxHeight + 10 + 'px';
      }
    }
  }
  //pc端调整外层包裹元素的宽度，不让智能预测图样式跑飞
  adjustWrapWidth() {
    const { islastArr } = this.props;
    const { cellCount, smartGuessStore: { smartGuessStatus, allMapshow }} = this.props;
    let screenWidth = document.body.clientWidth;
    let wfMapContainer = document.getElementById('smartGuessPicBox');
    let objWidth = cellCount*156 + (cellCount-1)*75 + 40;
    let header = document.getElementsByClassName('wf-map-header')[0];
    let smartMapWrap = document.getElementById('smart-map-wrap');
    if(header && smartMapWrap ) {
      let a = header.offsetHeight + 30;
      let b = 'calc(100% - '+ a + 'px)';
      smartMapWrap.style.height = b;
      smartMapWrap.style.overflow = 'auto'
    }
    if(wfMapContainer.offsetWidth != objWidth && smartGuessStatus && !allMapshow){ //防止包裹元素相同宽度重复触发宽高设置
      wfMapContainer.style.width = objWidth + 'px';
      wfMapContainer.style.minWidth = objWidth + 'px';
      wfMapContainer.style.marginLeft = '60px';
    }
     if(window.location.href.indexOf('isFromMobile') > -1 && islastArr) {
      wfMapContainer.style.width = objWidth + 'px';
      wfMapContainer.style.minWidth = objWidth + 'px';
      if(screenWidth > 400) {
        wfMapContainer.style.marginLeft = '40px';
      }
    }
  }
  //选择框选项选择具体项
  optionItemClick(obj,index) {
    const { smartGuessStore} = this.props;
    const { setOptionItem, setLoadingWrap } = smartGuessStore;
    if(window.parent.cancelLodingMask) {
      window.parent.cancelLodingMask('flex', true);
      setOptionItem(obj, index, window.parent.cancelLodingMask.bind(this, 'none'));
    } else {
      setLoadingWrap(true)
      setOptionItem(obj, index);
    }
  }

  //设置下拉选项
  setOptions(that, num, obj) {
    const { smartGuessStore} = this.props;
    const { setLoadingWrap } = smartGuessStore;
    let arr=[];
    for(let i=1; i<=num; i++) {
      let spanLabel = getLabel(528194,'第{num}条');
      spanLabel = spanLabel.replace(/{num}/,i);
      let obj = {
        key: i+'',
        selected: false,
        showname: spanLabel
      }
      arr.push(obj);
    }
    return arr.map((item, index) =>{
      return <li key={`option${index}`} onClick={that.optionItemClick.bind(this, obj, index)}>{item.showname}</li>
    });
  }

  //设置弹出的操作者信息面板
  setinfoPanel(info, e) {
    let screenWidth = document.body.clientWidth; 
    const { smartGuessStore:{ getOperator, clearOperatorArr, setHiddenSelectPanel } } = this.props;
    let isFromMobile = false;
    if((window.location.href.indexOf('isFromMobile') > -1) ) {
      isFromMobile = true;
    }
    clearOperatorArr();
    setHiddenSelectPanel();
    if(info.nodeOperatorName == '') {
      return
    }
    let isGroup = info.nodeOperatorName && info.nodeOperatorName.slice(0,1);
    if(isGroup!='1') { //未流经的节点不需要请求接口
      getOperator(info.nodeid, {cnodeid: info.nodeid, nodeType : info.nodeType});
    }
    e.stopPropagation();
    let props = info || {};
    let obj = null;
    if(!document.getElementById('wfFrontOperator-container')) {
      obj = document.createElement('div');
      obj.setAttribute('id', 'wfFrontOperator-container');
      document.body.appendChild(obj);
    } else {
      obj = document.getElementById('wfFrontOperator-container');
      obj.style.visibility = 'visible';
    }    
   
    if(isGroup == '1'){
      ReactDOM.render(<Panel ecId={`${this && this.props && this.props.ecId || ''}_Panel@99moe8`} 
        clickposX = {e.pageX}
        clickposY = {e.pageY} 
        isForOperator={true} 
        info={props} 
        isGroup={true}
        setoperator={this.setoperator} 
        isFromMobile={isFromMobile}
        store={this.props.smartGuessStore}/>, obj);
      } else {
        ReactDOM.render(<Panel ecId={`${this && this.props && this.props.ecId || ''}_Panel@mmbz0m`} 
          clickposX = {e.pageX}
          clickposY = {e.pageY} 
          isForOperator={true} 
          info={props} 
          isGroup={false}
          isFromMobile={isFromMobile}
          setoperator={this.setoperator} 
          store={this.props.smartGuessStore}/>, obj);
    }
  }

  //分叉节点，查看其他分支
  checkClick(data, e) {
    const { smartGuessStore} = this.props;
    const { setShowSelectPanel, isloading} = smartGuessStore;
    let obj = document.getElementById('wfFrontOperator-container');
    e.stopPropagation(); 
    setShowSelectPanel(data.nodeRemark);
    if(obj) {
      obj.style.visibility = 'hidden';
    }
  }

  getIcon(item) {
    if(item.nodeattribute == '1') {
      return (<i className="icon-coms02-coms-right-branch" />)  
    } 
    if(item.nodeattribute >= '3') {
      return (<i className="icon-coms02-coms-left-branch" /> )
    }
    if( item.ntype == '0') {
      return (<i className="icon-coms-organization-right" style={{fontSize: '20px'}} />)
    } 
    if(item.ntype == '1' ) {
      return (<i className="icon-coms02-coms-node" />)
    }
    if(item.ntype == '2') {
      return (<i className="icon-coms-Update-synchronization" style={{fontSize: '15px'}}/> )
    }
    if(item.ntype == '3') {
      return (<i className="icon-coms-Tile-o" /> )
    }
   
  }
 
  //画矩形
  drawRectangel(item, showStatus, checkItem) {
    const { isFromMobile, smartGuessStore } = this.props;
    const { isEnd } = smartGuessStore; 
    let spanLabel = getLabel(528191, '共{branchnumber}条分支，当前第{totalnum}条');
    spanLabel = spanLabel.toLowerCase();
    spanLabel = spanLabel.replace(/{branchnumber}/, parseInt(item.branchNumber));
    spanLabel = spanLabel.replace(/{totalnum}/, checkItem);
    switch(item.nodeid) {
      case -1: {return (
      <div className={'rectangle'} style={{border: `1px solid ${item.strokeColor}`}}>
        <div className={'content-wrap'}>
          <div className={'area left-area'} style={{backgroundColor: item.nodeColor, borderRight: `1px solid ${item.strokeColor}`}}>
            <img src="/images/ecology9/workflow/loading.gif"/>
          </div>
          <div className={'area right-area loading-word'}>
            <div className='info-content'>
              {/* <span>{item.nodeName}</span> */}
              <span >{getLabel(513959, '智能预测中')}</span>
            </div>
          </div>  
        </div>
      </div>
      )} break;
      case -2: {
        return (
          <div className={'rectangle  unKnownNode'}>
            <span></span>
            <span></span>
            <span></span>
          </div>
        )
      } break;
      default : {return (<div className={'rectangle'} style={{border:`1px solid ${item.strokeColor}`}}>
      <div className={'content-wrap'}  onClick={(event) => {this.setinfoPanel(item,event)}}>
        <div className={'area left-area'} style={{backgroundColor: item.nodeColor, borderRight: `1px solid ${item.strokeColor}`}}>
          {this.getIcon(item)}
        </div>
        <div className={'area right-area'}>
          <div className='info-content'>
            <span title={item.nodeName}>{item.nodeName}</span>
            <span title={this.setoperator(item.nodeOperatorName)}>{this.setoperator(item.nodeOperatorName)}</span>
          </div>
        </div>  
      </div>
      {isEnd && item.branchNumber > 1 && <div className={`select-node ${isFromMobile}`}>
      <span className='current-wf' title={spanLabel}>{spanLabel}</span>
    { <a className='check-others' onClick={(event) => {this.checkClick(item, event)}}>{getLabel(528167, '查看其他分支')}</a>}
      <div className={showStatus ?'select-box show-panel':'select-box'}>
        <ul className={'select-content'}>{this.setOptions(this, item.branchNumber, item)}</ul>
      </div>
    </div>}
      </div>)}
    }
  }
 
  //获取出口线条的颜色
  getLinkColor(obj) {
    const { data: {forecastLinkColor, passedLinkColor}} = this.props.smartGuessStore;
    switch(obj.nodeType) {
      case 0:  {
        return passedLinkColor;
      }; break; //已经流转过的节点
      default: {
        return forecastLinkColor; //预测节点
      }
    }
  } 
  //画流向箭头
  drawFlowPoint(obj, index, arrLength,color) {
    const {arrowPoint, arrowTurn, islastArr, isFromMobile} = this.props;
    return(
    <React.Fragment ecId={`${this && this.props && this.props.ecId || ''}_undefined@pa0uvw`}>
      {
        (index !== arrLength)  && <div className={`arrow-box  ${isFromMobile}`}>
          <div className={'line'} style={{borderBottom:`1px solid ${color}`}}></div>
          <div className={`arrow arrow-point-${arrowPoint}`}>
            <i className="jiantou icon-coms-organization-right" style={{color: color}}/>
          </div>
        </div> 
      } 
      {
        ((index == arrLength) && !islastArr) ? <div className={`arrow-last-box  ${isFromMobile}`}>
          <div className={`turn-arrow arrow-turn-${arrowTurn}`} style={{border: `2px solid ${color}`}}>
            <i className="jiantou icon-coms-organization-right" style={{color: color}}/>
          </div> 
        </div> : null
      } 
    </React.Fragment>
    )
  }

  //获取操作者面板信息
  setoperator(str) {
    let operatorArr = [];
    let operator = '';
    if(!str) return ' '
    if(str.indexOf('->') > -1) {
      // 处理节点被代理的情况
      let index = str.indexOf('->');
      let operatorA = str.slice(0, index);
      let operatorB = str.slice(index + 2);
      operatorArr = [...operatorArr, operatorA, operatorB];
    } else {
      operatorArr = [ str ]; 
    }
    operatorArr.length !== 0 && operatorArr.map( ( v, index ) => {
      let arr = [];
      arr = v.split('_');
      if(index !== operatorArr.length-1) {
        operator += arr[arr.length-1] + '->';
      } else {
        operator += arr[arr.length-1];
      }
    })  
    return operator;
  }

  render() {
    const {cellInfo = [], prefixCls='', isFromMobile} = this.props;
    const { smartGuessStore} = this.props;
    const { setShowSelectPanel, divideNodeArr=[]} = smartGuessStore;
    return (
      <div  class={`outer-wrap-box  ${prefixCls} ${isFromMobile}`}>
       {cellInfo.map((item,index) => {
        let showStatus=false, checkItem=1;
         if(toJS(divideNodeArr).length !== 0) {
           toJS(divideNodeArr).filter(v => {
            if(v.remark === item.nodeRemark) {
              showStatus = v.showStatus;
              checkItem = v.checkItem;
            }
          })
        }
        let showColor = this.getLinkColor(item);
         return (
           <React.Fragment ecId={`${this && this.props && this.props.ecId || ''}_undefined@l3241b@${index}`}> 
             {/* 实现转弯，要求先画矩形再画流向箭头 */}
            {this.drawRectangel(item, showStatus, checkItem)}
            {this.drawFlowPoint(item,index, cellInfo.length -1, showColor)}
           </React.Fragment>
         )
        })}
    </div>
    )
  }
}